const app = getApp()
import {
  imageUrl
} from "../../utils/imageutil.js"
Page({
  data: {
    imageUrl: imageUrl,
    multiIndex: [0, 0, 0, 0, 0],
    worktime: '',
    content: '',
    store_id: '',
    order_info: '',
    money: '',
    myDefaultAddress: null,
    cardlist: [], //会员卡信息
    cardcurr: -1,
    hyid: '', //会员id
    all_money: '', //总价
    is_simple_member: '',
    is_happiness_member: '',
    type: '',
    show: '',
    wallet: '', //余额
    year_card: '', //年卡
    sea_card: '', //月卡
    mon_card: '', //季卡
    use_wallet_money: '', //0不使用余额1使用

    integral: 0, //可抵扣服务指数
    happiness_integral: 0, //可抵扣幸福指数
    is_integral: 2, //是否使用服务指数
    is_happiness_integral: 2, //是否使用幸福指数

    integral_num: 0,
    happiness_integral_num: 0,

    is_com: 1, //要手续费 0不要
    proportion: 0.1, //手续费比例

    order_id: '',
    show_xfj: false,
    coupon: '',

    paytype_list: [
      // {title: "微信支付", paytype: 4}

    ],
    has_jump: false,
    show_code_img: false,

  },
  onLoad: function (options) {
    wx.removeStorageSync('change_address')
    let date = new Date()
    const month = date.getMonth()
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    this.setData({
      store_id: options.store_id,
      multiIndex: [0, month, day - 1, hour, minute]
    })
    this.getMyCar()
  },

  onShow() {
    if (wx.getStorageSync('change_address')) {
      let change_address = wx.getStorageSync('change_address')
      this.setData({
        ['order_info.address']: change_address.address,
        ['order_info.area']: change_address.area,
        ['order_info.doorplate']: change_address.doorplate,
        ['order_info.tel']: change_address.tel,
        ['order_info.user_name']: change_address.user_name,
        ['order_info.lat']: change_address.lat,
        ['order_info.lng']: change_address.lng,
        ['order_info.area_code']: change_address.area_code,
      })
    }
    if (this.data.has_jump) {
      getApp().showModal('是否已完成支付', true).then(() => {
        wx.reLaunch({
          url: '../matron/plan?order_id=' + this.data.order_id
        })
      })
      this.setData({
        has_jump: false
      })
    }
  },

  get_paytype() {
    getApp().globalData.post({
      url: '/api/applet.oyc/paytype.html',
      data: {
        storeid: this.data.order_info.store_id,
        houseid:""
      }
    }, true).then(res => {
      if (res.data.code == 1) {
        this.setData({
          paytype_list: res.data.data
        })
      
      } else {
        getApp().showModal(res.data.msg)
      }
    })
  },


  to_location() { //选择地址
    wx.navigateTo({
      url: '/pages/my/address?type=1',
    })
  },

  GetDkprice() {
    return new Promise((reslove, reject) => {
      app.globalData.post({
        data: {
          do: 'GetDkprice',
          uid: wx.getStorageSync('userInfo').id,
          price: this.data.order_info.money,
          is_happiness_integral: this.data.is_happiness_integral,
          is_integral: this.data.is_integral
        }
      }).then(res => {
        this.setData({
          integral: res.data.data.integral_price,
          happiness_integral: res.data.data.happiness_integral_price,
          integral_num: res.data.data.integral,
          happiness_integral_num: res.data.data.happiness_integral,
        })
        reslove()
      })
    })
  },

  getMyDefaultAddress() {
    app.globalData.post({
      data: {
        do: "MyDefaultAddress",
        user_id: wx.getStorageSync('userInfo').id
      }
    }).then(res => {
      if (res.data == false) {
        this.setData({
          myDefaultAddress: null,
          addressid: ''
        })
      } else {
        this.setData({
          myDefaultAddress: res.data,
          addressid: res.data.id,
          ['order_info.address']: res.data.address,
          ['order_info.doorplate']: res.data.doorplate,
          ['order_info.area']: res.data.area,
          ['order_info.user_name']: res.data.user_name,
          ['order_info.tel']: res.data.tel,
          ['order_info.lat']: res.data.lat,
          ['order_info.lng']: res.data.lng,
        })
      }
    })
  },
  toMyAddress() {
    wx.navigateTo({
      url: '/pages/my/address',
    })
  },
  getTime(e) {
    this.setData({
      worktime: e.detail
    })
  },
  getcontent(e) {
    this.setData({
      content: e.detail.value
    })
  },
  to_address() {
    wx.navigateTo({
      url: '../matron/address',
    })
  },
  to_consume() {
    wx.navigateTo({
      url: '../my/consume?type=1',
    })
  },
  iscom() {
    // 判断商品是否要手续费
    return new Promise((reslove, reject) => {
      app.globalData.post({
        data: {
          do: 'iscom',
          dishes_id: this.data.order_info.good_id,
          uid: wx.getStorageSync('userInfo').id
        }
      }).then(res => {
        this.setData({
          is_com: res.data.code
        })
        reslove()
      })
    })
  },
  getMyCar() { //获取信息
    app.globalData.post({
      data: {
        do: 'MyCar',
        store_id: this.data.store_id,
        user_id: wx.getStorageSync('userInfo').id
      }
    }).then(res => {
      console.log(res.data)
      this.setData({
        order_info: res.data.res[0],
        all_money: res.data.money,
      })
      this.get_paytype()
      this.getGetUserCleanGift()
    })
  },
  pay(money, order_id) {
    let _this = this;
    let paytype_list = this.data.paytype_list
    let itemList = []
    paytype_list.forEach((v, i) => {
      itemList.push(v.title)
    })
    wx.showActionSheet({
      itemList,
      success: (r) => {
        let tapIndex = r.tapIndex
        let paytype = paytype_list[tapIndex].paytype
        if(paytype==6){
          wx.setStorageSync('pay_info',{
            do: 'pay',
            paytype,
            openid: wx.getStorageSync('userInfo').openid,
            money: money,
            order_id: order_id
          })
          wx.navigateTo({
            url: '/online_bank/list?id=' + order_id
          })
          return
        }
        app.globalData.post({
          data: {
            do: 'pay',
            paytype,
            openid: wx.getStorageSync('userInfo').openid,
            money: money,
            order_id: order_id
          }
        }).then(res => {
          if (res.data.pay_status == 2) {
            wx.showModal({
              title: '提示',
              content: '支付成功',
              showCancel: false,
              success: () => {
                wx.reLaunch({
                  url: '../matron/plan?order_id=' + order_id
                })
              }
            })
            return
          }
          if (getApp().globalData.appletpayves_info.work == 3) {
            getApp().payPlugin(res.data.orderNo).then(() => {
              getApp().showModal('支付成功').then(() => {
                _this.Getcoupon(order_id)
              })
            }).catch(() => {
              wx.showToast({
                title: "取消支付",
                icon: "loading",
                duration: 1e3
              })
            })
            return
          }
          if (res.data.jump) {
            this.selectComponent('#zfb_pay').get_code(res.data.jump)
            this.setData({
              show_code_img: true,
              has_jump: true,
            })
            return
          } else {
            this.setData({
              has_jump: false
            })
          }
          // console.log("走到这来了",res.data.data.timeStamp);
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            complete: function (t) {
              "requestPayment:fail cancel" == t.errMsg && (wx.showToast({
                title: "取消支付",
                icon: "loading",
                duration: 1e3
              }), setTimeout(function () {
                wx.reLaunch({
                  url: '../matron/plan?order_id=' + order_id
                })
              }, 1e3)), "requestPayment:ok" == t.errMsg && (_this.Getcoupon(order_id));
            }
          });
        })

      }
    })

  },
  Getcoupon(order_id) {
    app.globalData.post({
      data: {
        do: 'Getcoupon',
        a: 'wxapp2',
        order_id: order_id
      }
    }).then(res => {
      this.setData({
        show_xfj: true,
        coupon: res.data.data.coupon
      })
    })
  },
  confirm() {
    this.setData({
      show_xfj: false
    })
    wx.reLaunch({
      url: '../matron/plan?order_id=' + this.data.order_id
    })
  },
  getAddOrder() {
    if (this.data.worktime == "") {
      wx.showToast({
        title: '请选择上门时间',
        icon: "none"
      })
      return false;
    }
    app.globalData.post({
      data: {
        do: 'addOrderV2',
        user_id: this.data.order_info.user_id, //用户id
        store_id: this.data.order_info.store_id, //商家id
        money: this.data.order_info.money, //付款金额
        combination_id: this.data.order_info.combination_id,
        tel: this.data.order_info.tel, //电话
        name: this.data.order_info.user_name, //姓名
        doorplate: this.data.order_info.doorplate,
        address: this.data.order_info.address, //地址
        note: this.data.content, //备注
        area: this.data.order_info.area, //区域
        lat: this.data.order_info.lat, //经度
        lng: this.data.order_info.lng, //纬度
        area_code: this.data.order_info.area_code,
        delivery_time: this.data.worktime, //送达时间
        pay_type: 1, //1.微信支付4.货到付款2.余额支付
        hyid: this.data.hyid, //会员ID
        use_wallet_money: this.data.use_wallet_money,
        integral_money: this.data.integral, //服务指数折扣
        happiness_integral: this.data.happiness_integral,
        is_integral: this.data.is_integral,
        is_happiness_integral: this.data.is_happiness_integral,
        sz: JSON.stringify([{
          "name": this.data.order_info.name,
          "img": this.data.order_info.logo,
          "num": this.data.order_info.num,
          "money": this.data.order_info.money,
          "dishes_id": this.data.order_info.good_id,
          "spec": this.data.order_info.spec,
          "is_qg": this.data.order_info.is_qg
        }]),
      }
    }).then(res => {
      console.log(res.data.data)
      if (res.data.status == 2) {
        wx.navigateTo({
          url: '../order/index',
        })
      } else {
        this.setData({
          order_id: res.data.data
        })
        this.pay(this.data.order_info.money, res.data.data)
      }
    })
  },
  getGetUserCleanGift() { //获取会员
    this.iscom().then(() => {
      app.globalData.post({
        data: {
          do: 'GetUserCleanGift',
          uid: wx.getStorageSync('userInfo').id
        }
      }).then(res => {
        this.setData({
          year_card: res.data.result.year_card,
          sea_card: res.data.result.sea_card,
          mon_card: res.data.result.mon_card,
          wallet: res.data.result.wallet,
        })
        if (!res.data.result.is_simple_member) {
          // 非会员
          let price = Number(this.data.order_info.money)
          if (this.data.is_com == 1) {
            this.setData({
              all_money: Number(price + price * this.data.proportion).toFixed(2),
              desc_money: "含手续费10%",
              show: 1,
              // use_wallet_money:1,
            })
          } else {
            this.setData({
              all_money: Number(price).toFixed(2),
              desc_money: "",
              show: 1,
              // use_wallet_money:1,
            })
          }

          this.getMembershipList()
        } else {
          // 会员
          let money = Number(this.data.order_info.money) //套餐价格
          let integral = Number(res.data.result.integral) //服务指数
          let happiness_integral = Number(res.data.result.happiness_integral) //幸福指数
          let use_integral = 0; //可使用的服务指数
          let use_happiness_integral = 0; //可使用的幸福指数
          if (integral >= money * 0.2) {
            use_integral = money * 0.2
          } else {
            use_integral = integral
          }
          if (happiness_integral >= money * 0.2) {
            use_happiness_integral = money * 0.2
          } else {
            use_happiness_integral = happiness_integral
          }
          let all_money = this.data.order_info.money
          this.setData({
            is_simple_member: res.data.result.is_simple_member, //是否幸福会员
            is_happiness_member: res.data.result.is_happiness_member, //是否超有幸福会员
            show: 2,
            integral: use_integral.toFixed(2), //
            happiness_integral: use_happiness_integral.toFixed(2),
            use_wallet_money: 0,
            all_money: Number(all_money).toFixed(2)
          })
        }
      })
    })
  },
  // 获取会员卡状态
  getMembershipList() {
    app.globalData.post({
      data: {
        do: 'MembershipList',
        uid: wx.getStorageSync('userInfo').id
      }
    }).then(res => {
      this.setData({
        cardlist: res.data.result
      })
    })
  },
  // 选择会员卡
  change_cardcurr(e) {
    this.setData({
      cardcurr: e.currentTarget.dataset.index,
      hyid: e.currentTarget.dataset.id,
    })
    this.getshowmoney()
  },
  change_iscard(e) {
    this.setData({
      iscard: !this.data.iscard
    })
    if (this.data.iscard) {
      this.getshowmoney()
    } else {
      this.setData({
        cardcurr: -1,
        hyid: ''
      })
      this.getshowmoney()
    }
  },
  // 金额计算
  getshowmoney() {
    if (this.data.show == 2) {
      let integral = 0
      let happiness_integral = 0
      if (this.data.is_integral == 1) {
        integral = this.data.integral
      }
      if (this.data.is_happiness_integral == 1) {
        happiness_integral = this.data.happiness_integral
      }
      this.setData({
        all_money: Number(this.data.order_info.money) - integral - happiness_integral,
        desc_money: "已优惠￥" + (integral + happiness_integral),
      })
      return
    }
    if (this.data.cardcurr == -1) {
      //未选会员卡
      let price = Number(this.data.order_info.money)
      if (this.data.is_com == 1) {
        this.setData({
          all_money: price + price * this.data.proportion,
          desc_money: "含手续费10%",
        })
      } else {
        this.setData({
          all_money: price,
          desc_money: "",
        })
      }
    } else if (this.data.cardcurr == 0) {
      // 幸福会员
      if (this.data.is_simple_member) {
        this.setData({
          all_money: this.data.order_info.money,
        })
      } else {
        this.setData({
          all_money: Number(this.data.order_info.money) + Number(this.data.cardlist[this.data.cardcurr].list[0].price),
          desc_money: "含 ¥" + this.data.cardlist[this.data.cardcurr].list[0].price + this.data.cardlist[this.data.cardcurr].title
        })
      }
    } else {
      // 超有幸福会员
      if (this.data.is_happiness_member) {
        this.setData({
          all_money: this.data.order_info.money,
        })
      } else {
        this.setData({
          all_money: Number(this.data.order_info.money) + Number(this.data.cardlist[this.data.cardcurr].list[0].price),
          desc_money: "含 ¥" + this.data.cardlist[this.data.cardcurr].list[0].price + this.data.cardlist[this.data.cardcurr].title
        })
      }
    }
  },

  change_is_integral(e) {
    if (e.detail.value.length > 0) {
      this.setData({
        is_integral: e.detail.value[0]
      })
    } else {
      this.setData({
        is_integral: 2
      })
    }
    this.GetDkprice().then(() => {
      this.getshowmoney()
    })
  },
  change_is_happiness_integral(e) {
    if (e.detail.value.length > 0) {
      this.setData({
        is_happiness_integral: e.detail.value[0]
      })
    } else {
      this.setData({
        is_happiness_integral: 2
      })
    }
    this.GetDkprice().then(() => {
      this.getshowmoney()
    })
  },
  to_hyqy() {
    wx.navigateTo({
      url: '/pages/my/hyqy',
    })
  },
})